package com.tfswx.ruleengine.fn;

import com.greenpineyu.fel.context.FelContext;
import com.tfswx.ruleengine.compute.exception.AppException;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ricky
 * @date 2021/8/19
 */
public class ConvertNyr extends BaseFn {

    private static Pattern pattern = Pattern.compile("((\\d+)年)?((\\d+)月)?((\\d+)天)?");

    // 每年的天数
    private static double n = (365 * 3 + 366) / 4.0;
    private static double y = (365 * 3 + 366) / 4.0 / 12.0;

    public static void main(String[] args) {
        String str = "2年0天";
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            String group2 = matcher.group(2);
            String group4 = matcher.group(4);
            String group6 = matcher.group(6);
            int nian = group2 == null ? 0 : Integer.parseInt(group2);
            int yue = group4 == null ? 0 : Integer.parseInt(group4);
            int tian = group6 == null ? 0 : Integer.parseInt(group6);
        }
    }

    @Override
    public Object call(Object[] arguments, FelContext context) {
        String str = String.valueOf(arguments[0]);
        String dw = String.valueOf(arguments[1]);
        if (StringUtils.isBlank(str)) {
            return 0;
        }
        if (StringUtils.isBlank(dw)) {
            throw new AppException("参数错误（y/m/d）三选一");
        }
        int nian = 0;
        int yue = 0;
        int tian = 0;
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()) {
            String group2 = matcher.group(2);
            if (group2 != null) {
                nian = Integer.parseInt(group2);
            }
            String group4 = matcher.group(4);
            if (group4 != null) {
                yue = Integer.parseInt(group4);
            }
            String group6 = matcher.group(6);
            if (group6 != null) {
                tian = Integer.parseInt(group6);
            }
        }

        double total = nian * n + yue * y + tian;
        switch (dw) {
            case "y":
                return total / n;
            case "m":
                return total / y;
            case "d":
                return total;
            default:
                throw new AppException("参数错误（y/m/d）三选一");
        }
    }

    @Override
    public List<Param> getParams() {
        List<Param> params = new ArrayList<>();
        params.add(new Param("x年x月x天"));
        params.add(new Param("y/m/d"));
        return params;
    }

    @Override
    public String getZwmc() {
        return "x年x月x天转为指定单位的数字";
    }


    @Override
    public String getName() {
        return "convertNyr";
    }
}
